package com.i2works.smartluolong.utils.common;


import com.i2works.smartluolong.utils.base.DateConstant;
import com.i2works.smartluolong.utils.base.GlobalConstant;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * 邮件发送服务
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2016/5/25 12:30
 */
@Component
public class EmailUtil {
    //private ThreadPoolTaskExecutor taskExecutor;
    private TaskExecutor taskExecutor;              //注入Spring封装的异步执行器
    private JavaMailSender mailSender;              //注入spring封装的邮件发送者
    private SimpleMailMessage simpleMailMessage;    //注入spring封装的SimpleMailMessage
    private String from;                            //发送者邮箱
    private String to;                              //接收者邮箱
    private String userName;                        //接收者邮箱
    private String subject;                         //标题
    private String content;                         //内容
    private boolean validate = false;               //是否需要身份验证

    public TaskExecutor getTaskExecutor() {
        return taskExecutor;
    }

    public void setTaskExecutor(TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }

    public JavaMailSender getMailSender() {
        return mailSender;
    }

    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }


    public SimpleMailMessage getSimpleMailMessage() {
        return simpleMailMessage;
    }

    public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
        this.simpleMailMessage = simpleMailMessage;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public boolean isValidate() {
        return validate;
    }

    public void setValidate(boolean validate) {
        this.validate = validate;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    /**
     * 执行发送
     *
     * @param userName 接收者姓名
     * @param email    接收者邮箱
     * @param sendType 邮件类型（1找回密码，2注册）
     */
    public void execute(Integer userId, String userName, String email, Integer sendType) {
        //当前时间
        String currentTime = DateUtils.get(DateConstant.ALL);
        try {
            this.setTo(email);
            this.setUserName(userName);
            String tempText = userId + "::" + System.currentTimeMillis();
            String dateCode = "";//DesUtil.encrypt(tempText);
            String siteName = "";//Global.getSiteName();
            String pcUrl = "";//Global.getHomePage();
            switch (sendType) {
                //注册成功
                case GlobalConstant.email.REGISTER_TYPE:
                    //标题
                    this.setSubject(GlobalConstant.email.REGISTER_TITLE + " - " + siteName);
                    this.setContent("<p><span style=color:red;>" + userName + "</span>，您好：</p><p>恭喜您在本站的账号注册成功，请通过下面的链接完成激活操作：</p><p>" + pcUrl + "user/checkRegister/" + dateCode + "</p><p>注意：本链接将在3个小时后失效。</p>--------------------------------<p>" + siteName + "</p><p>" + currentTime + "</p>");
                    break;
                //找回密码
                case GlobalConstant.email.PASSWORD_TYPE:
                    //标题
                    this.setSubject(GlobalConstant.email.PASSWORD_TITLE + " - " + siteName);
                    this.setContent("<p><span style=color:red;>" + userName + "</span>，您好：</p><p>您在本站使用了找回密码功能，请通过下面的链接完成操作：</p><p>" + pcUrl + "user/resetPassword/" + dateCode + "</p><p>注意：本链接将在3个小时后失效。</p>--------------------------------<p>" + siteName + "</p><p>" + currentTime + "</p>");
                    break;
                default:
                    //没有执行任何
                    break;
            }
            taskExecutor.execute(this::sendHtml);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 发送普通文本邮件
     */
    public void sendText() {
        mailSender = this.getMailSender();
        simpleMailMessage.setTo(this.getTo()); //接收人
        simpleMailMessage.setFrom(simpleMailMessage.getFrom()); //发送人,从配置文件中取得
        simpleMailMessage.setSubject(this.getSubject());
        simpleMailMessage.setText(this.getContent());
        mailSender.send(simpleMailMessage);
    }

    /**
     * 发送普通Html邮件
     */
    public void sendHtml() {
        try {
            mailSender = this.getMailSender();
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
            messageHelper.setTo(this.getTo());
            messageHelper.setFrom(simpleMailMessage.getFrom());
            messageHelper.setSubject(this.getSubject());
            messageHelper.setText(this.getContent(), true);
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送普通带一张图片的Html邮件
     * <p/>
     * Content="<html><head></head><body><img src=\"cid:image\"/></body></html>";
     * 图片必须这样子：<img src='cid:image'/>
     */
    public void sendHtmlWithImage(String imagePath) {
        try {
            mailSender = this.getMailSender();
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setTo(this.getTo());
            messageHelper.setFrom(simpleMailMessage.getFrom());
            messageHelper.setSubject(this.getSubject());
            messageHelper.setText(this.getContent(), true);
            FileSystemResource img = new FileSystemResource(new File(imagePath));
            messageHelper.addInline("image", img);
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送普通带附件的Html邮件
     */
    public void sendHtmlWithAttachment(String filePath) throws Exception {
        try {
            mailSender = this.getMailSender();
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            messageHelper.setTo(this.getTo());
            messageHelper.setFrom(simpleMailMessage.getFrom());
            messageHelper.setSubject(this.getSubject());
            messageHelper.setText(this.getContent(), true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            messageHelper.addAttachment(file.getFilename(), file);
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
